import pathToRegexp from 'path-to-regexp'

// const getFlatMenuKeys = (data, system) => {
//   let keys = [];
//   data.forEach(item => {
//     item.system === system && keys.push(item.key || item.path);
//     if (item.children) {
//       keys = keys.concat(getFlatMenuKeys(item.children, system));
//     }
//   });
//   return keys;
// };

export const getFlatMenuKeys = (...args) => Object.keys(getFlatMenus(...args))

const reg = /(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(?::\d+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/;

export function isUrl(path) {
  return reg.test(path);
}

export const getFlatMenus = (data, filterFn) => {
  let result = {};
  data.forEach(item => {
    if (filterFn(item)) {
      result[item.key || item.path] = item;
    }
    if (item.children) {
      result = {
        ...result,
        ...getFlatMenus(item.children, filterFn)
      }
    }
  });
  return result;
};

export const urlToList = (url) => {
  const urllist = url.split('/').filter(i => i);
  return urllist.map((urlItem, index) => `/${urllist.slice(0, index + 1).join('/')}`);
}
export const getMenuMatches = (flatMenuKeys, path) =>
  flatMenuKeys.filter(item => {
    if (item) {
      return pathToRegexp(item).test(path);
    }
    return false;
  });